package Threads.Patterns;


//二阶段终止，可以优雅的暂停程序
public class TwoPhaseTermination {
    public static void main(String[] args) throws InterruptedException {
        TPT tpt=new TPT();
        tpt.start();
        Thread.sleep(5000);
        System.out.println("stop the running monitor thread");
        tpt.stop();
    }
    public static class TPT{
        private  Thread moniterThread; // thread doing things

        private volatile  boolean stop=false; //flag of stop，volatile保证线程间可见性

        private boolean starting=false; //flag of start

        //start thread
        public void start(){
            synchronized (this){
                if (starting)
                    return;
                starting=true;
            }
            moniterThread=new Thread(()->{
                while (true){
                    Thread current=Thread.currentThread();
                    if (stop){
                        System.out.println("I am interuppted");
                        System.out.println("handle before die");
                        break;
                    }
                    try {
                        System.out.println("doing something");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"monitor");
            moniterThread.start();

        }

        //stop the thread
        public void stop(){
            stop=true;
            moniterThread.interrupt();
        }
    }
}
